# code:utf8
import json
from datetime import datetime
from zc_core.model.items import Catalog, Brand, Supplier, Sku, ItemData, OrderItem, MissItemData, MissSku, \
    ItemDataSupply
from pyquery import PyQuery
from zc_core.util.http_util import fill_link
from suzhou.matcher import *
from zc_core.util.common import parse_number, parse_time, parse_int
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code, parse_sp_sku_id


def parse_catalog(response):
    jpy = PyQuery(response.text)
    div_list = jpy('div.all-goods > div.category_line_height')

    cats = list()
    for div in div_list.items():
        # 一级分类
        cat1_name = div('div.product h3 span').text()
        cat1_id = md5(cat1_name)
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)
        # 二级分类
        cat2_dls = div('div.product-wrap > div > dl')
        for cat2_dl in cat2_dls.items():
            cat2_name = cat2_dl('dt span').text().strip()
            cat2_id = md5(cat2_name)
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

            # 三级分类
            cat3_as = cat2_dl('dd a')
            for cat3_a in cat3_as.items():
                cat3_name = cat3_a.text().strip()
                cat3_id = match_cat_id(cat3_a.attr('href'))
                cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1

    return cat


# 解析brand列表
def parse_brand(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    a_list = jpy('dl.dl_brands_more dd a')
    brands = list()
    for br in a_list.items():
        brand = Brand()
        br_id = match_brand_id(br.attr('href'))
        br_name = clean_text(br.attr('title'))
        brand['id'] = md5(br_name)
        brand['code'] = br_id
        brand['name'] = br_name
        brand['batchNo'] = meta.get('batchNo')
        brands.append(brand)

    return brands


# 解析brand列表
def parse_supplier(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    a_list = jpy('ul.gys a')
    suppliers = list()
    for sp in a_list.items():
        sp_id = match_supplier_id(sp.attr('href'))
        sp_name = sp.text()
        supplier = Supplier()
        supplier['id'] = md5(sp_name)
        supplier['code'] = sp_id
        supplier['name'] = sp_name
        supplier['batchNo'] = meta.get('batchNo')
        suppliers.append(supplier)

    return suppliers


# 解析sku列表
def parse_sku_page(response):
    jpy = PyQuery(response.text)
    txt_node = jpy('nav.pagination3 > span.next + span')
    if txt_node:
        return parse_int(txt_node.text().replace('共', '').replace('页', ''))

    return 0


# 解析sku列表
def parse_sku(response, cat3_map=None):
    meta = response.meta
    cat3_id = meta.get('catalog3Id')
    jpy = PyQuery(response.text)
    div_links = jpy('div.gp-list-view ul li div.info')
    sku_list = list()
    for sku_div in div_links.items():
        sku = Sku()
        link = sku_div('div.img a').attr('href')
        spu_id, sku_id = match_sku_id_from_sku(link)
        sku['skuId'] = sku_id
        sku['spuId'] = spu_id
        if cat3_id:
            sku['catalog3Id'] = cat3_id
        elif spu_id and cat3_map and cat3_map.contains(spu_id):
            sku['catalog3Id'] = cat3_map.get(spu_id)

        sku['supplierName'] = sku_div('div.source font.textm').text()
        sku['sameCount'] = sku_div('div.source > span.fr').text().replace('个报价', '')
        sku_list.append(sku)

    if not len(sku_list):
        print(f'cat={cat3_id}, page={meta.get("page")}')

    return sku_list


# 解析sku列表
def parse_search_list(response):
    jpy = PyQuery(response.text)
    div_links = jpy('div.gp-list-view ul li div.info')
    sku_list = list()
    for sku_div in div_links.items():
        sku = Sku()
        link = sku_div('div.img a').attr('href')
        tp = match_sku_id_from_sku(link)
        sku['skuId'] = tp[1]
        sku['spuId'] = tp[0]
        sku['soldCount'] = int(sku_div('p.sales-num').text().replace('销量：', ''))
        sku['srcType'] = 'search'
        sku_list.append(sku)

    return sku_list


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    offline = jpy('div.goods_price b:contains("此商品已下架，欢迎选购其他商品。")')
    if offline:
        return None

    result = ItemData()
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    spu_id = meta.get('spuId')
    cat3_id = meta.get('catalog3Id')

    result['batchNo'] = batch_no
    result['spuId'] = spu_id
    result['skuId'] = sku_id
    result['catalog3Id'] = cat3_id

    result['skuName'] = jpy('div.goods_price span.product_title').attr('title').strip()
    images = jpy('div.spec-scroll div.items li img')
    if images:
        result['skuImg'] = images.eq(0).attr('src').strip()

    # 价格、销量
    sale_price = jpy('div.summary_price strong#price_tag').text()
    origin_price = jpy('dl.gwj div.summary_gprice').text()
    sold_count = jpy('div.goods_price > div.summary > div.summary_right > dl').eq(0)('dt.fl').text()
    result['salePrice'] = parse_number(sale_price)
    result['originPrice'] = parse_number(origin_price)
    result['soldCount'] = parse_number(sold_count)
    # 品牌
    brand_name = _get_attr(jpy, '品牌：')
    if brand_name:
        brand_id = md5(brand_name)
        if brand_id and brand_name:
            result['brandId'] = brand_id
            result['brandName'] = brand_name
    # 型号
    result['brandModel'] = _get_attr(jpy, '型号：')
    # 单位
    result['unit'] = _get_attr(jpy, '计量单位：')

    # 供应商商品链接
    sp_sku_link = jpy('dl.gwj dd a').attr('href')
    result['supplierSkuLink'] = sp_sku_link
    # 供应商
    supplier = jpy('div.tips a font.textm')
    if supplier:
        sp_name = supplier.text().strip()
        result['supplierId'] = md5(sp_name)
        result['supplierName'] = sp_name
        sp_sku_id = _get_attr(jpy, '商品编码：')
        if not sp_sku_id:
            sp_sku_id = parse_sp_sku_id(sp_sku_link)
        result['supplierSkuId'] = sp_sku_id
        result['supplierSkuCode'] = sp_sku_id

    # 主详图
    _parse_imgs(jpy, result)
    # 参数
    _parse_attrs(jpy, result)

    result['genTime'] = datetime.utcnow()

    return result


# 处理同款,存储sku
def parse_sku_fx(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog3_id = meta.get('catalog3Id')

    jpy = PyQuery(response.text)
    for data in jpy('.goods_other li').items():
        link = data('.border')('a').attr('href')
        sku = Sku()
        re_data = re.search('(\d+).*?(\d+)', link)
        sku['skuId'] = re_data.group(2)
        sku['spuId'] = re_data.group(1)
        sku['catalog3Id'] = catalog3_id
        sku['batchNo'] = batch_no
        sku['supplierName'] = data('a').text()
        yield sku


def _get_attr(jpy, attr):
    # 型号
    attr_node = jpy(f'div.detail_info_content div.detail_info_content_item:contains("{attr}")')
    if attr_node:
        attr_val = attr_node.eq(0).text()
        if attr_val:
            return attr_val.replace(attr, '').strip()


def _parse_imgs(jpy, result):
    main_imgs = jpy('div.spec-scroll div.items li img')
    if main_imgs:
        main_images = list()
        result['mainImgs'] = main_images
        for img in main_imgs.items():
            main_images.append(img.attr('src').strip())

    detail_imgs = jpy('div#product_details li.detail_info div.tagHtml0 img')
    if detail_imgs:
        detail_images = list()
        result['detailImgs'] = detail_images
        for img in detail_imgs.items():
            if img.attr('src'):
                detail_images.append(img.attr('src').strip())


def parse_certs(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    jpy = PyQuery(response.text)
    cert_imgs = jpy('div.empower_content div.empower_main img')
    if cert_imgs:
        result = ItemDataSupply()
        result['batchNo'] = batch_no
        result['skuId'] = sku_id

        certs = list()
        result['certs'] = certs
        for img in cert_imgs.items():
            src = fill_link(img.attr('src').strip(), 'http://www.zfcgwssc.suzhou.gov.cn')
            certs.append(src)

        return result


def _parse_attrs(jpy, result):
    # 型号
    attrs = {}
    jpy('')
    attr_rows2 = jpy(f'li#tagContent1 table.product_param tbody tr')
    if attr_rows2:
        param_list = []
        attrs['param_list'] = param_list
        for tr in attr_rows2.items():
            key = tr('td').eq(0).text()
            val = tr('td').eq(1).text()
            if key:
                param_list.append({'key': key, 'val': val})
    # 清理商品参数
    jpy(f'li#tagContent1 table.product_param').remove()
    # 获取标签参数
    tag_attr_table = jpy(f'li#tagContent1 table')
    if tag_attr_table:
        attr_rows1 = tag_attr_table.eq(0)('tbody tr')
        if attr_rows1:
            tag_list = []
            attrs['tag_list'] = tag_list
            for tr in attr_rows1.items():
                key = tr('td').eq(0).text()
                val = tr('td').eq(1).text()
                if key:
                    tag_list.append({'key': key, 'val': val})

    result['attrs'] = attrs


# 解析参数列表
def parse_params(response):
    jpy = PyQuery(response.text)
    trs = jpy('table.Ptable tr')
    order_detail_url = 'http://210.76.73.185/more_notices.html?mall_show=true&no={}'
